package BeenChina.PM.Action;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import net.sf.json.JSONArray; 
import BeenChina.PM.Model.ModelEmpInfoUnitWorkEmp;
import BeenChina.PM.Model.ModelEmpInfoWorkEmp;
import BeenChina.PM.Model.ModelUser;
import BeenChina.PM.Service.ServiceFactory;
import BeenChina.PM.Util.EncodeDownLoadFileName;
import BeenChina.PM.Util.ExportInfo;
import BeenChina.PM.Util.ExportToExcel;
import BeenChina.PM.Util.StringUtil;
import BeenChina.PM.Util.xmlSerializer;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class EmpInfoWorkEmpQueryAction extends ActionSupport {
  
	private static final long serialVersionUID = 1L;	
	private Map<String, Object> tableData;  
	
	private InputStream excelStream;  
	private String fileName;
	private static String EXPORTID = "121";
	private boolean exportExcel; 
	private static final Log log = LogFactory.getLog(CaseNumberEfficiencyQuery.class);
	
	public boolean isExportExcel() {
		return exportExcel;
	} 
	
	 
	public InputStream getExcelStream() {
		return excelStream;
	}

	public void setExcelStream(InputStream excelStream) {
		this.excelStream = excelStream;
	}

	public String getFileName() throws UnsupportedEncodingException {		
		ServletActionContext.getResponse().setHeader("charset","UTF-8");
		fileName = EncodeDownLoadFileName.encode(ServletActionContext.getRequest(), fileName); 
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	
	public Map<String, Object> getTableData() {
		return tableData;
	}

	private String dateFrom,dateTo;
	
	public void setDateFrom(String dateFrom){
		this.dateFrom = dateFrom;
	}

	public void setDateTo(String dateTo){
		this.dateTo = dateTo;
	}
	
	@Override
	public String execute()	{
		ModelUser user = (ModelUser) ActionContext.getContext().getSession().get("user");
		if (user!=null)
		  exportExcel = user.concatPermission(EXPORTID);
  		return "load";
	}
	
	private List<ModelEmpInfoWorkEmp> getEmpInfoWorkEmp() throws Exception { 
		
		try{
			 if (StringUtil.isDate(dateFrom) && 
				 StringUtil.isDate(dateTo)  )
			 
				return   ServiceFactory.getInstance().getBaseInfoService().selectEmpInfoWorkEmp(dateFrom, dateTo);			 				
			 
			 else {
				 return null;
			}
		 }
		 catch(Exception exp){
			 throw exp;
		 }
	}
	
	private List<ModelEmpInfoUnitWorkEmp> getEmpInfoUnitWorkEmp()throws Exception { 
		
		try{
			 if (StringUtil.isDate(dateFrom) && 
				 StringUtil.isDate(dateTo)  )
			 
				return   ServiceFactory.getInstance().getBaseInfoService().selectEmpInfoUnitWorkEmp(dateFrom, dateTo);
			 
			 else {
				 return null;
			}
		 }
		 catch(Exception exp){
			 throw exp;
		 }
	}
	
	 public String refreshData() throws Exception
	 {
		 List<ModelEmpInfoWorkEmp> empInfoWorkEmps = getEmpInfoWorkEmp();
		 List<ModelEmpInfoUnitWorkEmp> empInfoUnitWorkEmps =getEmpInfoUnitWorkEmp();
		 
		 Map<String, Object> map = new HashMap<String, Object>();   
		 
		 map.put("EmpInfoWorkEmpTable", getEmpInfoWorkEmpTable(empInfoWorkEmps)); 
		 map.put("EmpInfoUnitWorkEmpTable", getEmpInfoUnitWorkEmpTable(empInfoUnitWorkEmps)); 
		 tableData = map;
		 
	     return ActionSupport.SUCCESS; 
	     
	 }

	private JSONArray getEmpInfoUnitWorkEmpTable(
			List<ModelEmpInfoUnitWorkEmp> list) {
 
		 
		 JSONArray mapDetailTable = new JSONArray();
		 if (list ==null || list.size() ==0)
		 {
			 return mapDetailTable;
		 }
		 
		 //folder
		 JSONArray jsonFolder = new JSONArray();
		 jsonFolder.add("合計");
		 
		 JSONArray jsonTittle = new JSONArray(); 
		 jsonTittle.add("ユニット(人)");		 
		 
		 String firstday = list.get(0).getDate();
		 
		 Integer sumday = 0;
		 for (ModelEmpInfoUnitWorkEmp model : list) {
			 String nextday = model.getDate();
			 if (!nextday.equals(firstday))
			{
				jsonFolder.add(sumday);
		  	    jsonTittle.add(firstday. substring(5) ) ;
				firstday = nextday;
				sumday = model.getEmpCount();
			} else {
				sumday += model.getEmpCount();
			}
		}
	 	// add last item		 
		 jsonTittle.add(firstday. substring(5));	
		 jsonFolder.add(sumday);
		 
		 mapDetailTable.add(jsonTittle);
		 
		   firstday = list.get(0).getDate();
		 List<ModelEmpInfoUnitWorkEmp> resultHeader = new ArrayList<ModelEmpInfoUnitWorkEmp>();
		 for (int i = 0; i < list.size(); i++) {
			 ModelEmpInfoUnitWorkEmp model = list.get(i);
			 
			  if (model.getDate().equals(firstday))
			  {
				  resultHeader.add(model);
			  }
		}
		 
		 for (int i = 0; i < resultHeader.size(); i++) {
			 ModelEmpInfoUnitWorkEmp modelH = resultHeader.get(i);
			 
			 JSONArray json = new JSONArray();	 
			 json.add(modelH.getUnit()); 
			 
			 for (int j = 0; j < list.size(); j++) {
				 ModelEmpInfoUnitWorkEmp model = list.get(j); 
				 
				 if ( modelH.getUnit().equals(model.getUnit())){
					 
					 json.add( model.getEmpCount());
				 }
			}
			 
			 mapDetailTable.add(json);
		}
		 
	
		 //todo folder
		 mapDetailTable.add(jsonFolder);
		 return mapDetailTable; 
		 
	}

	private JSONArray  getEmpInfoWorkEmpTable(
			List<ModelEmpInfoWorkEmp> list) {
		
		JSONArray json = new JSONArray();	
		JSONArray map = new JSONArray(); 
		
		if (list==null || list.size()==0){
			return map;
		}
		
		 Map<String, JSONArray> detail = new  HashMap<String, JSONArray>();			
			
		 json = new JSONArray();json.add("超級<br>");detail.put("SuperLevel",json);
		 json = new JSONArray();json.add("高級<br>");detail.put("SeniorLevel",json);	
		 json = new JSONArray();json.add("一級<br>");detail.put("OneLevel",json);
		 json = new JSONArray();json.add("二級<br>");detail.put("TwoLevel",json);
		 json = new JSONArray();json.add("三級<br>");detail.put("ThreeLevel",json);
		 json = new JSONArray();json.add("四級<br>");detail.put("FourthLevel",json);
		 json = new JSONArray();json.add("五級<br>");detail.put("FiveLevel",json);	
		 json = new JSONArray();json.add("Eチェック<br>");detail.put("ECheck",json);	
		 json = new JSONArray();json.add("Tr人数 <br>【新規&五級】");detail.put("TrainOPCount",json);	
		 json = new JSONArray();json.add("Unit人数<br>【本番】");detail.put("UnitOPCount",json);	
		 json = new JSONArray();json.add("OP人数<br>【Tr+Unit】");detail.put("OPCount",json);	
		 json = new JSONArray();json.add("全体人数<br>【Tr+Unit+E】");detail.put("EmpCount",json);
		 
		 
		 JSONArray jsonTittle = new JSONArray();		 
		 jsonTittle.add("級別/分類(人)");
		 for (int i = 0; i < list.size(); i++) {
			 ModelEmpInfoWorkEmp model = list.get(i); 
		     
			  
			 jsonTittle.add(model.getDate(). substring(5));
			 detail.get("SuperLevel").add(model.getSuperLevel());
			 detail.get("SeniorLevel").add(model.getSeniorLevel());
			 detail.get("OneLevel").add(model.getOneLevel());
			 detail.get("TwoLevel").add(model.getTwoLevel());
			 detail.get("ThreeLevel").add(model.getThreeLevel());
			 detail.get("FourthLevel").add(model.getFourthLevel());
			 detail.get("FiveLevel").add( model.getFiveLevel()); 
			 detail.get("ECheck").add( model.getEcheck());
			 detail.get("TrainOPCount").add( model.getTrainOPCount());
			 detail.get("UnitOPCount").add( model.getUnitOPCount());
			 detail.get("OPCount").add( model.getOpCount());
			 detail.get("EmpCount").add( model.getEmpCount());
			 
		 }
		 
		 map.add(jsonTittle);
		 map.add( 	 detail.get("SuperLevel") );
		 map.add( 	 detail.get("SeniorLevel" ));
		 map.add( 	detail.get("OneLevel") );
		 map.add( 	detail.get("TwoLevel") );
		 map.add( 	detail.get("ThreeLevel") );
		 map.add( 	detail.get("FourthLevel") );
		 map.add( 	detail.get("FiveLevel") ); 
		 map.add( 	detail.get("ECheck") );
		 map.add( 	detail.get("TrainOPCount") );
		 map.add( 	detail.get("UnitOPCount") );
		 map.add( 	detail.get("OPCount") );
		 map.add( 	detail.get("EmpCount") );
		 
		 return map;
	}
	
	public String export() throws Exception{		 
		try{	  
				 
			String file=ServletActionContext.getServletContext().getRealPath("WEB-INF/excel/EmpInfoWorkEmpQuery.xls");
			 List<ModelEmpInfoWorkEmp> empInfoWorkEmps = getEmpInfoWorkEmp();
			 List<ModelEmpInfoUnitWorkEmp> empInfoUnitWorkEmps =getEmpInfoUnitWorkEmp();
			 
		 	 	 
			 
			Map<String, JSONArray> map = new HashMap<String, JSONArray>();   
			
			map.put("職人員数統計情報",  getEmpInfoWorkEmpTable(empInfoWorkEmps));
			map.put("ユニット在職人員数統計情報",getEmpInfoUnitWorkEmpTable(empInfoUnitWorkEmps)); 	  

			ByteArrayOutputStream out = new ByteArrayOutputStream(); 		
			this.setFileName("在職人数検索"+ this.dateFrom +"~"+ this.dateTo); 					
			String infoFile=ServletActionContext.getServletContext().getRealPath("WEB-INF/excel/EmpInfoWorkEmpQuery.xml");
			List<ExportInfo> infoList = (new xmlSerializer<List<ExportInfo>>()).read(infoFile);
			
			ExportToExcel.export(file, map, infoList,out);
			
			setExcelStream(new ByteArrayInputStream(out.toByteArray()));	   			   			      
			out.close();
		
			return ActionSupport.SUCCESS;
		}
		catch(Exception exp){
			log.error(exp);
			return ActionSupport.ERROR;
		}		
	}
	
}
